package com.example.work1

import android.content.Context
import android.content.Intent
import android.content.res.Configuration
import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.view.Gravity
import android.view.View
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.content.edit
import java.util.*

class MainActivity : AppCompatActivity() {
    private lateinit var languageSpinner: Spinner
    private lateinit var textView: TextView
    private lateinit var button: Button
    private lateinit var imageView: ImageView
    private val preferences by lazy { getSharedPreferences("Settings", Context.MODE_PRIVATE) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setupLayout()
        setupLanguageSpinner()
        setupButton()
    }

    private fun setupLayout() {
        val rootLayout = LinearLayout(this).apply {
            orientation = LinearLayout.VERTICAL // 设置布局方向为垂直
            layoutParams = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT
            )
            gravity = Gravity.CENTER_VERTICAL // 垂直居中所有组件
        }

        imageView = ImageView(this).apply {
            layoutParams = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT // 宽度100%，高度自适应
            ).apply {
                bottomMargin = 24.dpToPx(context) // 增加底部外边距
            }
            setImageResource(R.drawable.flag)
        }
        rootLayout.addView(imageView)

        textView = TextView(this).apply {
            layoutParams = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT // 宽高自适应
            ).apply {
                gravity = Gravity.CENTER_HORIZONTAL
                topMargin = 24.dpToPx(context)
                bottomMargin = 16.dpToPx(context)
            }
            text = getString(R.string.textView)
            textSize = 24f
        }
        rootLayout.addView(textView)

        languageSpinner = Spinner(this).apply {
            layoutParams = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT // 宽高自适应
            ).apply {
                gravity = Gravity.CENTER_HORIZONTAL
                topMargin = 16.dpToPx(context)
                bottomMargin = 16.dpToPx(context)
            }
        }
        rootLayout.addView(languageSpinner)

        button = Button(this).apply {
            layoutParams = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT // 宽高自适应
            ).apply {
                gravity = Gravity.CENTER_HORIZONTAL
                topMargin = 16.dpToPx(context)
                bottomMargin = 24.dpToPx(context)
            }
            text = getString(R.string.button)
            textSize = 20f
        }
        rootLayout.addView(button)

        setContentView(rootLayout)
    }

    // 扩展函数，用于将dp转换为px
    private fun Int.dpToPx(context: Context): Int =
        (this * context.resources.displayMetrics.density).toInt()

    private fun setupLanguageSpinner() {
        val currentLanguage = preferences.getString("My_Lang", Locale.getDefault().language)
        val adapter: ArrayAdapter<CharSequence> = ArrayAdapter.createFromResource(
            this, R.array.language_options, android.R.layout.simple_spinner_item
        ).apply {
            setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        }
        languageSpinner.adapter = adapter

        val spinnerPosition = LanguageCode.fromCode(currentLanguage).ordinal
        languageSpinner.setSelection(spinnerPosition, true)

        languageSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(
                parent: AdapterView<*>, view: View?, position: Int, id: Long
            ) {
                val selectedLanguage = LanguageCode.entries[position].code
                setLocale(selectedLanguage)
            }

            override fun onNothingSelected(parent: AdapterView<*>) {}
        }
    }

    private fun setupButton() {
        button.setOnClickListener {
            // 获取在屏幕上的位置
            val location = IntArray(2)
            it.getLocationOnScreen(location)
            val x = location[0]
            val y = location[1]

            // 打印或显示按钮的位置
            Log.d("ButtonPosition", "Button is at: x = $x, y = $y")

            textView.text = getString(R.string.clicked)
        }
    }

    private fun setLocale(lang: String?) {
        val appLang = lang ?: Locale.getDefault().language
        if (preferences.getString("My_Lang", "") != appLang) {
            val locale = Locale(appLang)
            Locale.setDefault(locale)
            val config = Configuration().apply { setLocale(locale) }
            resources.updateConfiguration(config, resources.displayMetrics)
            preferences.edit { putString("My_Lang", appLang) }
            restartActivity()
        }
    }

    private fun restartActivity() {
        val refresh = Intent(this, MainActivity::class.java)
        refresh.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
        startActivity(refresh)
    }

    enum class LanguageCode(val code: String?) {
        DEFAULT(null), CHINESE("zh"), RUSSIAN("ru");

        companion object {
            fun fromCode(code: String?): LanguageCode = entries.find { it.code == code } ?: DEFAULT
        }
    }
}